package com.zhongying.jf.util;

import com.alibaba.fastjson.JSON;
import com.chinazyjr.framework.common.config.HConfig;
import com.hk.bank.util.HttpClient;
import com.zhongying.jf.ResConstants;
import com.zhongying.jf.exception.ZhongyingiException;
import com.zhongying.jf.model.hkjf.ReqAssetDto;
import com.zhongying.jf.model.hkjf.ResFundsDto;
import com.zhongying.jf.util.sign.SignUtil;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.text.SimpleDateFormat;
import java.util.*;

public class HttpForHKDUtil {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(HttpForHKDUtil.class);

    //私钥
    //private static final String privateKey = HConfig.GLOBAL.getProperty("HKDprivateKey");

    private static final String public_key_path = HConfig.GLOBAL.getProperty("public_key_path");


    public static ResFundsDto<T> RequestHttpPost(String url, ReqAssetDto reqAssetDto, String contractNo){
        //接收返回结果
        ResFundsDto<T> resultDto = new  ResFundsDto<T>();
        try {
            String HKDPrivateKey = SignUtil.loadKeyByFile(public_key_path, "HKDPrivateKey.keystore");
            //UUID
            String requestUuid = UUID.randomUUID().toString().replaceAll("-", "");
            //时间戳
            String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

            reqAssetDto.setPlatform("HKJF");

            reqAssetDto.setRequestUuid(requestUuid);

            reqAssetDto.setTimestamp(timestamp);

            //翻转为map
            TreeMap<String,String> signMap = new TreeMap<>();
            signMap.put("requestUuid",requestUuid);
            signMap.put("contractNo",contractNo);

            //签名
            String  sign = SignUtil.sign(HKDPrivateKey,signMap);
            //设置签名
            reqAssetDto.setSign(sign);
            //转为json
            String data = JSON.toJSONString(reqAssetDto);

            Map requestMap = new HashMap();
            //封裝數據
            requestMap.put("data",data);

            LOGGER.info("调用豪康贷 请求参数:"+data);
            //发送请求
            HttpClient client = new HttpClient(url);

            String result = "";

            client.sendPost(requestMap);
            //返回结果
            result = client.getResult();

            LOGGER.info("满标回调返回参数result:" +result);

            resultDto = JSON.parseObject(result, ResFundsDto.class);

            LOGGER.info("满标回调返回参数resultDto:" +resultDto.toString());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("请求豪康贷异常信息:" +e.getMessage());
            throw new ZhongyingiException(ResConstants.HKD_EXCEPTION.getCode(), ResConstants.HKD_EXCEPTION.getMsg()+e.getMessage());
        }

        return resultDto;
    }


}
